package com.xinting.piano;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.test.ApplicationTestCase;
import android.test.mock.MockContext;
import android.util.Log;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import com.xinting.piano.app.PDialog;
import com.xinting.piano.data.PApp;
import com.xinting.piano.data.PMelody;
import com.xinting.piano.lib.network.PNetWork;
import com.xinting.piano.lib.storage.PSharePreferences;
import com.xinting.piano.lib.storage.PStorage;
import com.xinting.piano.lib.util.PUtil;
import com.xinting.piano.service.IHandleJson;
import com.xinting.piano.service.PAccount;
import com.xinting.piano.service.PAlbum;
import com.xinting.piano.service.PBroadcast;
import com.xinting.piano.service.PCommentService;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
 */
public class ApplicationTest extends ApplicationTestCase<Application> {

    public static final String LOG_TAG = PApp.LOG_TAG+"_test";
    private Context context;

    public ApplicationTest() {
        super(Application.class);
        context = new Activity();
    }

    public void testNetWork() {
    }

    public void testNetWork2() {
        Map<String, String> params = new HashMap<>();
        params.put(PAccount.KEY_TOKEN, "MjkzNTQ0fDEzMjk3OTMxODEw");
        try {
            PNetWork.getInstance().post(PUtil.joinURL(PApp.URL_SERVER, PAlbum.URL_MELODY), params, new PNetWork.IHandleHttpResult() {
                @Override
                public void onRequest(Request req, IOException e) {
                    Log.e(PApp.LOG_TAG, req.toString() + "-" + e.getMessage());
                }

                @Override
                public void onResponse(Response res) throws IOException {
                    ResponseBody body = res.body();
                    Log.i(PApp.LOG_TAG, body.contentType().toString() + "-" + body.bytes().length + "-" + body.contentLength());
                }
            });
        } catch (IOException e) {
            Log.e(PApp.LOG_TAG, e.getMessage());
        }
    }

    public void testDownloadFile() {
        OkHttpClient client = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add(PAccount.KEY_TOKEN, "MjkzNTQ0fDEzMjk3OTMxODEw");
        RequestBody body = builder.build();

        //Add Header
        String url = PUtil.joinURL(PApp.URL_SERVER, PAlbum.URL_MELODY);
        Request.Builder rBuilder = new Request.Builder();
        rBuilder.url(url);
        rBuilder.header("User-Agent", "Piano Application");
        Request request = rBuilder.post(body).build();

        try {
            Response response = client.newCall(request).execute();
            ResponseBody responseBody = response.body();
            InputStream is = responseBody.byteStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            File file = PStorage.getInstance().getFile("hello.3gp");
            FileOutputStream fos = new FileOutputStream(file);
            while ((count = is.read(buffer, 0, 1024)) > 0) {
                fos.write(buffer, 0, count);
            }
            fos.flush();
            is.close();
            fos.close();
        } catch (IOException e) {
            Log.e(PApp.LOG_TAG, e.getMessage());
        }
    }

    public void testLogin() {
        Map<String, String> params = new HashMap<>();
        params.put("username", "13297931810");
        params.put("passwd", "123123");
    }

    public void testCheckPhoneNumber() {
        assertEquals(false, PUtil.checkPhoneNumber("1329793180"));
        assertEquals(true, PUtil.checkPhoneNumber("13297931810"));
        assertEquals(false, PUtil.checkPhoneNumber("13291231203812"));
    }

    public void testCheckPasswd() {
        assertEquals(false, PUtil.checkPasswd("123"));
        assertEquals(true, PUtil.checkPasswd("12319204"));
        assertEquals(false, PUtil.checkPasswd("129312fdsfja9wfjadfadfadfadsfjaskdlfjasdkf"));
    }

    public void testSharePereferences() {
        Log.v(PApp.LOG_TAG, new PSharePreferences(PApp.getAppContext()).get(PAccount.KEY_TOKEN).toString());
    }

    public void testComments() {
        PMelody melody = new PMelody();
        melody.setId("2");
        PCommentService commentService = new PCommentService(melody);
        commentService.getMelodyComments(new IHandleJson() {
            @Override
            public void handleJson(JSONObject json) {
                Log.v(PApp.LOG_TAG, json.toString());
            }
        });
    }

    public void testRoutineService() {

    }

    public void testUTF8Decode() {
        String title = "%E6%88%91%E4%B8%8D%E7%9F%A5%E9%81%93";
        try {
            title = URLDecoder.decode(title, "UTF-8");
            Log.v(PApp.LOG_TAG, title);
        } catch (UnsupportedEncodingException e) {
            Log.e(PApp.LOG_TAG, e.getMessage());
        }
    }

    public void testBroadcast() {
        PBroadcast.getInstance().register(0, new PBroadcast.IListener() {
            @Override
            public void listen(Object data) {
                Log.v(PApp.LOG_TAG, data.toString());
            }
        });

        PBroadcast.getInstance().broadcast(0, "xinting");
    }

    public void testAssets() {
        try {
            getApplication().getAssets().open("about.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void testDate() {
        Date date = new Date("Sat Dec 12 04:00:48 2015");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Log.e(PApp.LOG_TAG, format.format(date));
    }

    public void testDecode() {
        String nick = "齐天大圣";
        String s = "%E5%A4%A9%E6%89%8D%E5%91%80%E5";
        String s1 = "%E9%BD%90%E5%A4%A9%E5%A4%A7%E5%9C%A3";
        try {
            Log.e(PApp.LOG_TAG, URLEncoder.encode(nick, "utf-8"));
            int e = Log.e(PApp.LOG_TAG, URLDecoder.decode(s, "UTF-8"));
            int e1 = Log.e(PApp.LOG_TAG, URLDecoder.decode(s1, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
    }

    public void testJson() {
        JSONObject obj = new JSONObject();
        JSONObject obj2 = new JSONObject();
        try {
            obj.put("obj2", obj2);
            Log.e(LOG_TAG, obj.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void testDialog() {
        PDialog dialog = new PDialog(context);
        dialog.setTitle("Hello");
        dialog.setContent("World");
        dialog.show();
    }

    public void testFormat() {
        Log.e(LOG_TAG, String.format("%d", 123l));
    }

}